<template>
  <div class="attend_detail">
    <div class="attend_detail_left">
      <div class="info_detail_title">
        <div class="opera-left">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            v-if="['3', '4'].includes(detail.status)"
            @click="edit()">
            编辑
          </el-button>
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-document-delete"
            v-if="detail.isCanZZ === '1'"
            @click="approvalData('5')">
            终止
          </el-button>
          <el-button
            size="mini"
            type="warning"
            plain
            icon="el-icon-s-promotion"
            v-if="detail.canRevoke === '1'"
            @click="approvalData('4')">
            撤回
          </el-button>
        </div>
        <span class="title_name">差旅费报销单</span>
        <div class="opera-right">
          <el-button size="mini" type="primary" @click="exportData">导出</el-button>
        </div>
      </div>
      <div class="right_box">
        <div class="attend_main">
          <div class="add_table" ref="add_table">
            <div class="add_tab">
              <div class="table_line line_th">
                <div class="table_tit">姓名</div>
                <div class="table_con">{{ auditForm.userName }}</div>
                <div class="table_tit">部门</div>
                <div class="table_con">{{ auditForm.orgName }}</div>
                <div class="table_tit">职务</div>
                <div class="table_con">{{ auditForm.post }}</div>
              </div>
              <div class="table_line">
                <div class="table_tit">关联单据</div>
                <div class="table_con con_all con_trans">
                  <div class="info_detail" v-if="auditForm.associatedForm">
                    {{ auditForm.associatedFormName }}
                  </div>
                  <div class="info_detail" v-else>未关联单据</div>
                </div>
              </div>
              <div class="table_line">
                <div class="table_tit">
                  证明人
                  <el-popover placement="bottom" width="300" trigger="hover" v-if="isWindow">
                    提示：证明人，若出差时无陪同人员，则无需填写，只有一个陪同人员且是负责人也无需填写
                    <i class="el-icon-info" slot="reference"></i>
                  </el-popover>
                </div>
                <div class="table_con con_all">
                  <template v-if="auditForm.certifierList && auditForm.certifierList.length">
                    <span v-for="(item, index) in auditForm.certifierList" :key="item.certifierId" class="partner">
                      {{ item.certifier }}
                      <span v-if="index < auditForm.certifierList.length - 1">、</span>
                    </span>
                  </template>
                </div>
              </div>
              <div class="table_line">
                <div class="table_tit">交通工具</div>
                <div class="table_con con_all con_trans">
                  <el-radio-group v-model="auditForm.transportation" disabled>
                    <el-radio label="1">公共交通-火车/高铁/客车/飞机</el-radio>
                    <el-radio label="2">公车</el-radio>
                    <el-radio label="3">平台租赁</el-radio>
                    <el-radio label="4">其他(请注明)</el-radio>
                  </el-radio-group>
                  <el-input
                    class="week_input"
                    placeholder="请注明其他"
                    v-model="auditForm.transportationRemark"
                    size="mini"
                    v-if="auditForm.transportation === '4'"
                    readonly></el-input>
                </div>
              </div>
              <div class="table_line">
                <div class="table_tit">出差事由</div>
                <div class="table_con con_all">
                  {{ auditForm.reimburseReason }}
                </div>
              </div>
              <div class="table_act">
                <div class="table_line">
                  <div class="table_tit">起程时间</div>
                  <div class="table_con">
                    <span v-if="auditForm.startTime">{{ auditForm.startTime.slice(0, -3) }}</span>
                  </div>
                  <div class="table_tit">离开时间</div>
                  <div class="table_con">
                    <span v-if="auditForm.endTime">{{ auditForm.endTime.slice(0, -3) }}</span>
                  </div>
                </div>
                <div class="table_line">
                  <div class="table_tit">起程地点</div>
                  <div class="table_con">
                    {{ auditForm.startPlace }}
                  </div>
                  <div class="table_tit">离开地点</div>
                  <div class="table_con">
                    {{ auditForm.leavePlace }}
                  </div>
                </div>
                <div class="table_line bill_head">
                  <div class="table_t1">
                    <div class="table_t2">
                      <div class="table_tit">车船费</div>
                    </div>
                    <div class="table_t2">
                      <div class="table_tit">单据张数</div>
                      <div class="table_tit">金额</div>
                    </div>
                  </div>
                  <div class="table_t1">
                    <div class="table_t2">
                      <div class="table_tit">住宿费</div>
                    </div>
                    <div class="table_t2">
                      <div class="table_tit">单据张数</div>
                      <div class="table_tit">金额</div>
                    </div>
                  </div>
                  <div class="table_t1">
                    <div class="table_t2">
                      <div class="table_tit">伙食补助/交通补助</div>
                    </div>
                    <div class="table_t2">
                      <div class="table_tit">天数</div>
                      <div class="table_tit">金额</div>
                    </div>
                  </div>
                  <div class="table_t1">
                    <div class="table_t2">
                      <div class="table_tit">其他费用</div>
                    </div>
                    <div class="table_t2">
                      <div class="table_tit">单据张数</div>
                      <div class="table_tit">金额</div>
                    </div>
                  </div>
                  <div class="table_t1 t1_last">
                    <div class="table_tit">单据张数</div>
                    <div class="table_tit">总计金额</div>
                  </div>
                </div>
                <div class="table_line bill_con" v-if="auditForm.expenseList">
                  <div class="bill_only">
                    <div class="table_con">
                      {{ auditForm.expenseList[0].billCount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[0].amount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[1].billCount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[1].amount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[2].dayCount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[2].amount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[3].billCount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.expenseList[3].amount }}
                    </div>
                  </div>
                  <div class="bill_all">
                    <div class="table_con">
                      {{ auditForm.billCount }}
                    </div>
                    <div class="table_con">
                      {{ auditForm.amountTotal }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="add_extra">
              <!-- <div class="add_link">
                <div class="add_label">关联单据：</div>
                <div class="link_info">
                  <div class="info_detail" v-if="auditForm.associatedForm">
                    {{ auditForm.associatedFormName }}
                  </div>
                  <div class="info_detail" v-else>
                    暂无数据
                  </div>
                </div>
              </div> -->
              <div class="add_bill" v-if="billAmount">
                <div class="add_label">发票信息：</div>
                <div class="annex_box">
                  <div class="annex_li" v-if="auditForm.expenseList[0].billCount">
                    <div class="annex_label">车船费：</div>
                    <div class="annex_upload">
                      <UploadPreview :file-list="auditForm.fareList" layout="block"></UploadPreview>
                    </div>
                  </div>
                  <div class="annex_li" v-if="auditForm.expenseList[1].billCount">
                    <div class="annex_label">住宿费：</div>
                    <div class="annex_upload">
                      <UploadPreview :file-list="auditForm.hotelList" layout="block"></UploadPreview>
                    </div>
                  </div>
                  <div class="annex_li" v-if="auditForm.expenseList[3].billCount">
                    <div class="annex_label">其他费用：</div>
                    <div class="annex_upload">
                      <UploadPreview :file-list="auditForm.otherExpenseList" layout="block"></UploadPreview>
                    </div>
                  </div>
                </div>
              </div>
              <div class="add_annex">
                <div class="add_label">附件：</div>
                <div class="annex_upload">
                  <UploadPreview :file-list="auditForm.enclosureList" layout="list"></UploadPreview>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="btn_check" v-if="detailInfo.saveStatus === '0'">
          <el-button size="small" type="primary" plain @click="edit()">编 辑</el-button>
          <el-button size="small" type="primary" @click="save()">提 交</el-button>
        </div>
        <div class="btn_check" v-if="firstType === '4' && detailInfo.saveStatus === '1' && detailInfo.status === '0'">
          <el-button size="small" type="primary" @click="approvalData('1')">通 过</el-button>
          <el-button size="small" type="danger" @click="approvalData('2')">不通过</el-button>
          <el-button size="small" type="danger" @click="approvalData('3')">退回</el-button>
        </div>
      </div>
    </div>
    <div class="attend_detail_r">
      <div class="add_r_title">审批流程</div>
      <expenseSteps ref="refsFlow" :activeInfo="detailInfo" />
    </div>
    <XnDialog
      title="审批意见"
      :visible.sync="dialogShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="50%"
      left="10vw"
      class="branch_dialog"
      @closed="dialogShow = false">
      <el-input
        type="textarea"
        v-model="suggest"
        placeholder="请输入审批意见"
        rows="5"
        maxlength="50"
        show-word-limit></el-input>
      <div class="btn_save">
        <el-button class="btnBorder" size="small" @click="dialogShow = false">取 消</el-button>
        <el-button size="small" class="btnBg" type="primary" @click="submit()">确认提交</el-button>
      </div>
    </XnDialog>
  </div>
</template>

<script>
import expenseSteps from './expenseSteps'
import UploadPreview from '@com/UploadPreview/index.vue'
import {
  getTripReimburseDetail,
  approveFormExpense,
  updateTripReimburse,
  exportTripExpenseExcel,
  checkIsCanRelated,
} from '@apis/api-dailyManage.js'
import moment from 'moment'
import XnDialog from '@com/xnDialog.vue'
import { cloneDeep } from 'lodash'
export default {
  components: {
    expenseSteps,
    UploadPreview,
    XnDialog,
  },
  props: {
    userType: {
      type: String,
      default: '',
    },
    firstType: {
      type: String,
      default: '',
    },
    activeInfo: {
      type: Object,
      default: () => {},
    },
    isWindow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      moment: moment,
      detail: {},
      detailInfo: {},
      dialogShow: false,
      suggest: '',
      userName: JSON.parse(localStorage.PSKH_USERINFO).userName,
      orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
      postName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.postName,
      auditForm: {
        id: '',
        formTitle: '差旅费报销单',
        formType: '2',
        certifierList: [
          // {
          //   userName: '',
          //   userId: '',
          // },
        ],
        billCount: '',
        transportation: '',
        transportationRemark: '',
        reimburseReason: '',
        startTime: '',
        endTime: '',
        startPlace: '',
        leavePlace: '',
        expenseList: [
          {
            amount: '',
            billCount: '',
            expenseType: '1',
          },
          {
            amount: '',
            billCount: '',
            expenseType: '2',
          },
          {
            amount: '',
            dayCount: '',
            expenseType: '3',
          },
          {
            amount: '',
            billCount: '',
            expenseType: '4',
          },
        ],
        amountTotal: '',
        userId: localStorage.pskh_userId,
        userName: JSON.parse(localStorage.PSKH_USERINFO).userName,
        orgId: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgId,
        orgName: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.orgName,
        post: JSON.parse(localStorage.PSKH_USERINFO).loginPostInfo.postName,
        enclosureList: [], // 附件
        fareList: [], // 车船费
        hotelList: [], // 住宿费
        otherExpenseList: [], // 其他费用
        associatedForm: '', // 关联单据ID
        associatedFormName: '',
      },
      approveType: '',
    }
  },
  computed: {
    billAmount() {
      if (
        this.auditForm.expenseList[0].billCount ||
        this.auditForm.expenseList[1].billCount ||
        this.auditForm.expenseList[3].billCount
      ) {
        return true
      } else {
        return false
      }
    },
  },
  watch: {
    activeInfo: {
      handler(news) {
        if (news.id) {
          this.detail = news
          this.getTripReimburseDetail()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {
    if (this.$route.query.id && this.$route.query.type === '2') {
      this.detail = cloneDeep(this.$route.query)
      this.getTripReimburseDetail()
    }
    if (this.$route.query.id) {
      this.clearUrl()
    }
  },
  methods: {
    approvalData(type) {
      this.approveType = type
      this.suggest = ''
      if (['2', '3'].includes(type)) {
        this.dialogShow = true
      } else if (['4', '5'].includes(type)) {
        const str = type === '4' ? '确认撤回该报销单吗？' : '确认终止该报销单吗？'
        this.$confirm(str, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.submit()
          })
          .catch(() => {})
      } else {
        this.submit()
      }
    },
    getTripReimburseDetail() {
      getTripReimburseDetail({
        id: this.detail.id,
      }).then(res => {
        if (res.code === 0) {
          this.detailInfo = res.data
          this.auditForm = Object.assign(this.auditForm, this.detailInfo)
          // console.log(this.auditForm)
        }
      })
    },
    removeHtmlStyle(html) {
      const rel = /style\s*?=\s*?([‘"])[\s\S]*?\1/g
      let newHtml = ''
      if (html) {
        newHtml = html.replace(rel, '')
      }
      return newHtml
    },
    submit() {
      if (['2', '3'].includes(this.approveType) && this.suggest.trim().length === 0) {
        this.$message.warning('请填写审批意见')
        return
      }
      approveFormExpense({
        content: this.suggest || '',
        id: this.detailInfo.id,
        processInstanceId: this.detailInfo.processInstanceId,
        status: this.approveType,
        taskId: this.detailInfo.taskId || '',
      }).then(res => {
        if (res.code === 0) {
          this.dialogShow = false
          if (['4', '5'].includes(this.approveType)) {
            const str1 = this.approveType === '4' ? '撤回成功' : '终止成功'
            this.$message.success(str1)
          } else {
            this.$message.success('审批成功')
          }
          this.$emit('addSuccess', 'detail')
        }
      })
    },
    edit() {
      this.$emit('editDia', this.auditForm)
    },
    save() {
      if (!this.auditForm.transportation) {
        return this.$message.warning('请选择交通工具')
      }
      if (this.auditForm.transportation === '4' && !this.auditForm.transportationRemark.trim().length) {
        return this.$message.warning('请注明其他类型交通工具')
      }
      if (!this.auditForm.reimburseReason.trim().length) {
        return this.$message.warning('请输入出差事由')
      }
      if (!this.auditForm.startTime) {
        return this.$message.warning('请选择起程时间')
      }
      if (!this.auditForm.endTime) {
        return this.$message.warning('请选择离开时间')
      }
      if (!this.auditForm.startPlace.trim().length) {
        return this.$message.warning('请输入出发地')
      }
      if (!this.auditForm.leavePlace.trim().length) {
        return this.$message.warning('请输入目的地')
      }
      if (!this.auditForm.amountTotal) {
        return this.$message.warning('请填写相关费用信息')
      }
      for (let i = 0; i < 4; i++) {
        const el = this.auditForm.expenseList[i]
        if (el.amount && ((!el.billCount && i !== 2) || (!el.dayCount && i === 2))) {
          return this.$message.warning('请填写完整的费用信息')
        }
        if (!el.amount && ((el.billCount && i !== 2) || (el.dayCount && i === 2))) {
          return this.$message.warning('请填写完整的费用信息')
        }
      }
      // if (!this.auditForm.associatedForm) {
      //   return this.$message.warning('请选择需要关联的单据')
      // }
      if (this.auditForm.expenseList[0].amount && !this.auditForm.fareList.length) {
        return this.$message.warning('请上传车船费相关发票信息附件图片')
      }
      if (this.auditForm.expenseList[1].amount && !this.auditForm.hotelList.length) {
        return this.$message.warning('请上传住宿费相关发票信息附件图片')
      }
      if (this.auditForm.expenseList[3].amount && !this.auditForm.otherExpenseList.length) {
        return this.$message.warning('请上传其他费用相关发票信息附件图片')
      }
      if (!this.auditForm.expenseList[0].amount) {
        this.auditForm.fareList = []
      }
      if (!this.auditForm.expenseList[1].amount) {
        this.auditForm.hotelList = []
      }
      if (!this.auditForm.expenseList[3].amount) {
        this.auditForm.otherExpenseList = []
      }
      const param = {
        ...this.auditForm,
        saveStatus: '1',
      }
      if (this.auditForm.associatedForm) {
        checkIsCanRelated({
          id: this.auditForm.associatedForm,
        }).then(res => {
          if (res.data === '1') {
            this.dialogTip(param)
          } else {
            this.$alert('出差前审批单已被关联，请选择其他表单', '提示', {
              confirmButtonText: '确定',
            })
          }
        })
      } else {
        this.dialogTip(param)
      }
    },
    exportData() {
      const req = `?id=${this.detail.id}`
      const link = document.createElement('a')
      link.target = 'targetName'
      link.href = exportTripExpenseExcel(req)
      link.click()
      link.remove()
    },
    dialogTip(param) {
      this.$confirm('请确认当前报销金额与票据数量是否正确，确定后不可修改。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          updateTripReimburse(param).then(res => {
            if (res.code === 0) {
              this.$message.success('提交成功')
              this.$emit('addSuccess', '1')
            }
          })
        })
        .catch(() => {})
    },
    clearUrl() {
      const url = window.location.href
      const urlArr = url.split('?')
      window.history.replaceState(null, null, urlArr[0])
      this.$route.query.id = ''
      this.$route.query.type = ''
      this.$route.query.formType = ''
      this.$route.query.flag = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.attend_detail {
  height: 100%;
  font-size: 15px;
  display: flex;
  overflow: auto;
  .attend_detail_left {
    height: 100%;
    // width: calc(100% - 300px);
    flex: 1;
    min-width: 760px;
  }
  .attend_detail_r {
    flex: 1;
    width: 300px;
    min-width: 300px;
    height: 99%;
    padding: 10px;
    border-left: 1px solid #ececec;
    overflow-y: auto;
    margin-bottom: 10px;
    min-height: 380px;
    .add_r_title {
      font-size: 15px;
      font-weight: bold;
      margin-bottom: 10px;
    }
  }
  .info_detail_title {
    height: 50px;
    line-height: 50px;
    font-weight: bold;
    font-size: 20px;
    padding-left: 20px;
    text-align: center;
    position: relative;
    .opera-right {
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translateY(-50%);
    }
    .opera-left {
      position: absolute;
      left: 20px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .right_box {
    height: calc(100% - 60px);
    width: 100%;
    .attend_main {
      width: 100%;
      padding: 0 20px;
      height: calc(100% - 50px);
      margin: 0 auto;
      overflow-y: auto;
    }
    .add_table {
      .add_tab {
        margin-top: 15px;
        border-top: 1px solid #d0d7e0;
        border-left: 1px solid #d0d7e0;
        .table_line {
          display: flex;
          align-items: stretch;
          justify-content: space-around;
          color: #333333;
          .table_tit {
            padding: 15px 0;
            font-weight: 600;
            font-size: 15px;
            background-color: #e9eff48f;
            .el-icon-info {
              color: #999999;
              margin-left: 5px;
            }
          }
          .table_tit,
          .table_con {
            width: 25%;
            border-right: 1px solid #d0d7e0;
            border-bottom: 1px solid #d0d7e0;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .con_all {
            width: 75%;
            justify-content: start;
            padding: 0 10px;
            flex-wrap: wrap;
            .partner {
              display: inline-block;
            }
          }
          .con_trans {
            flex-wrap: wrap;
            /deep/.el-radio-group {
              padding: 10px 0;
              .is-disabled {
                .is-checked {
                  .el-radio__inner {
                    border-color: #2b78f1 !important;
                    background: #2b78f1 !important;
                    &::after {
                      background-color: #ffffff;
                    }
                  }
                }
                .el-radio__inner {
                  border-color: #dcdfe6 !important;
                  background: #ffffff !important;
                }
                .el-radio__label {
                  color: #606266;
                }
              }
            }
            .week_input {
              width: 100%;
              border: 1px solid #d0d7e0;
              margin: 0 0 10px;
            }
          }
          .el-date-editor {
            width: 100%;
          }
          .el-radio {
            margin-right: 10px;
          }
          /deep/.el-input__inner {
            border: none;
            border-radius: 0;
            width: 100%;
          }
        }
        .table_act {
          position: relative;
          .icon_box {
            position: absolute;
            right: -35px;
            top: 50%;
            transform: translateY(-50%);
            color: #4a79ba;
            font-size: 30px;
            display: flex;
            flex-direction: column;
            cursor: pointer;
            span {
              margin: 5px 0;
            }
          }
          .bill_head {
            .table_t1 {
              width: 20%;
              .table_t2 {
                display: flex;
                align-items: center;
                .table_tit {
                  flex: 1;
                }
              }
            }
            .t1_last {
              display: flex;
              align-items: center;
              .table_tit {
                height: 100%;
                width: 50%;
              }
            }
          }
          .bill_con {
            display: flex;
            .bill_only {
              width: 80%;
              display: flex;
              align-items: stretch;
              .table_con {
                flex: 1;
                min-height: 50px;
                white-space: pre-wrap;
                word-break: break-all;
                padding: 0 5px;
              }
            }
            .bill_all {
              width: 20%;
              display: flex;
              align-items: stretch;
              .table_con {
                width: 50%;
                min-height: 50px;
                white-space: pre-wrap;
                word-break: break-all;
                padding: 0 5px;
              }
            }
          }
        }
        .table_total {
          .table_tit {
            width: 100%;
          }
          .bill_con {
            display: flex;
            .bill_only {
              width: 80%;
              display: flex;
              align-items: stretch;
              .table_con {
                flex: 1;
              }
            }
            .bill_all {
              width: 20%;
              .table_con {
                width: 100%;
              }
            }
            .table_con {
              padding: 15px 0;
            }
          }
        }
      }
      .add_extra {
        margin-top: 15px;
        color: #333333;
        .add_label {
          font-weight: 600;
        }
        .add_link {
          display: flex;
          align-items: center;
          .link_info {
            margin-left: 10px;
            flex: 1;
            position: relative;
          }
          .info_detail {
            border: 1px dashed #d0d7e0;
            padding: 8px;
            width: 100%;
            font-size: 14px;
          }
        }
        .add_bill {
          margin-top: 15px;
          .annex_box {
            border: 1px dashed #d0d7e0;
            margin-top: 15px;
            padding: 10px 20px;
            .annex_li {
              display: flex;
              .annex_label {
                width: 80px;
                min-width: 80px;
                font-weight: 600;
                font-size: 15px;
              }
              /deep/.el-image {
                width: 130px !important;
                height: 90px !important;
                .wj_img {
                  width: inherit !important;
                  height: inherit !important;
                }
              }
            }
          }
        }
        .add_annex {
          display: flex;
          margin-top: 15px;
          .annex_upload {
            flex: 1;
          }
        }
      }
    }
    .btn_check {
      margin-top: 10px;
      margin-right: 10px;
      text-align: right;
    }
  }
  .size_input {
    ::-webkit-outer-spin-button,
    ::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }

    input[type='number']::-webkit-outer-spin-button,
    input[type='number']::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }
  }
}
.branch_dialog {
  /deep/.el-dialog__body {
    padding-left: 20px;
    padding-right: 20px;
    min-height: 0;
    .el-radio {
      margin-right: 20px;
    }
    .el-textarea {
      margin: 20px 0;
    }
    .btn_save {
      text-align: right;
    }
  }
}
</style>
<style lang="scss">
.viewer-prev,
.viewer-next {
  display: inline-block !important;
}
</style>
